// 老的浏览器可能根本没有实现 mediaDevices，所以我们可以先设置一个空的对象
if (navigator.mediaDevices === undefined) {
    navigator.mediaDevices = {}
}

// 一些浏览器部分支持 mediaDevices。我们不能直接给对象设置 getUserMedia
// 因为这样可能会覆盖已有的属性。这里我们只会在没有getUserMedia属性的时候添加它。
if (navigator.mediaDevices.getUserMedia === undefined) {
    navigator.mediaDevices.getUserMedia = function(constraints) {
        // 首先，如果有getUserMedia的话，就获得它
        var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia

        // 一些浏览器根本没实现它 - 那么就返回一个error到promise的reject来保持一个统一的接口
        if (!getUserMedia) {
            return Promise.reject(new Error('getUserMedia is not implemented in this browser'))
        }

        // 否则，为老的navigator.getUserMedia方法包裹一个Promise
        return new Promise(function(resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject)
        })
    }
}

navigator.mediaDevices
    .getUserMedia({
        // audio: true,
        video: true
    })
    .then(function(stream) {
        var video = document.querySelector('video')
        // 旧的浏览器可能没有srcObject
        if ('srcObject' in video) {
            video.srcObject = stream
        } else {
            // 防止在新的浏览器里使用它，应为它已经不再支持了
            video.src = window.URL.createObjectURL(stream)
        }
        video.onloadedmetadata = function(e) {
            video.play()
        }
    })
    .catch(function(err) {
        console.log(err.name + ': ' + err.message)
    })

const fs = require('fs')
const path = require('path')
const dayjs = require('dayjs')
const db = require('./db.js')
const Vue = require('vue/dist/vue.common.js')
const canvas = document.createElement('canvas')
canvas.height = 480
canvas.width = 640
const { remote } = require('electron')
const { Menu, MenuItem, dialog, ipcMain } = remote

const app = new Vue({
    el: '#app',
    data() {
        return {
            code: '',
            timeString: '',
            categories: [],
            rfItemList: [],
            last10: []
        }
    },
    methods: {
        findByCategory(category) {
            return this.rfItemList.filter(v => v.FNO === category)
        },
        grant() {
            const index = this.rfItemList.findIndex(v => v.RFcode === this.code)
            this.code = ''
            if (index === -1) {
                this.play('编号错误')
                return
            }
            const item = this.rfItemList[index]
            const imageFileName = `图片/${item.RFcode} ${item.sskb} ${this.timeString.replace(/:/g, '-')} ${Date.now()}.png`
            if (item.rfzt === '领用') {
                item.rfzt = '归还'
                this.play('归还成功')
                db.insert(item.RFcode, item.sskb, '归还', this.timeString.split(' ')[0], this.timeString.split(' ')[1], imageFileName)
            } else {
                item.rfzt = '领用'
                this.play('领用成功')
                db.insert(item.RFcode, item.sskb, '领用', this.timeString.split(' ')[0], this.timeString.split(' ')[1], imageFileName)
            }
            this.saveImage(imageFileName)
            this.last()
        },
        async play(name) {
            this.$refs.player.src = path.join(process.cwd(), name + '.wav')
            this.$refs.player.play()
        },
        async saveImage(fileName) {
            // const canvas = this.$refs.canvas
            const ctx = canvas.getContext('2d')
            ctx.drawImage(this.$refs.video, 0, 0, 640, 480)
            const base64Data = canvas.toDataURL().replace(/^data:image\/\w+;base64,/, '')
            // var dataBuffer = new Buffer(base64Data, 'base64') // 解码图片
            const dataBuffer = Buffer.from(base64Data, 'base64') // 这是另一种写法
            fs.writeFile(fileName, dataBuffer, function(err) {
                if (err) console.log(err)
            })
        },
        async last() {
            this.last10 = await db.findLast10()
        },
        select(rfcode) {
            let selectWin = new remote.BrowserWindow({
                parent: remote.getCurrentWindow(),
                minWidth: 1024,
                minHeight: 768,
                center: true,
                modal: true,
                show: false,
                webPreferences: {
                    nodeIntegration: true
                }
            })
            selectWin.loadFile('select.html')
            selectWin.on('ready-to-show', () => {
                selectWin.show()
                selectWin.setSize(1280, 768)
                selectWin.center()
            })
            selectWin.webContents.on('did-finish-load', () => {
                selectWin.webContents.send('ping', rfcode)
            })
            selectWin.on('closed', () => {
                selectWin = null
            })
            // ipc.send('select', rfcode)
        },
        focus() {
            this.$refs.rfcode.focus()
        },
        add(FNO) {
            let menu = new Menu() //new一个菜单//添加菜单功能
            menu.append(
                new MenuItem({
                    label: `在 ${FNO} 中添加`,
                    click: () => {
                        let editWin = new remote.BrowserWindow({
                            parent: remote.getCurrentWindow(),
                            minWidth: 1024,
                            minHeight: 768,
                            center: true,
                            modal: true,
                            show: false,
                            webPreferences: {
                                nodeIntegration: true
                            }
                        })
                        editWin.loadFile('edit.html')
                        editWin.on('ready-to-show', () => {
                            editWin.show()
                            editWin.setSize(1280, 768)
                            editWin.center()
                        })
                        editWin.webContents.on('did-finish-load', () => {
                            editWin.webContents.send('add', FNO)
                        })
                        editWin.on('closed', () => {
                            editWin = null
                            this.fetch()
                        })
                    }
                })
            )
            menu.popup(remote.getCurrentWindow())
            this.focus()
        },
        edit(item) {
            let menu = new Menu() //new一个菜单//添加菜单功能
            menu.append(
                new MenuItem({
                    label: `在 ${item.FNO} 中添加`,
                    click: () => {
                        let editWin = new remote.BrowserWindow({
                            parent: remote.getCurrentWindow(),
                            minWidth: 1024,
                            minHeight: 768,
                            center: true,
                            modal: true,
                            show: false,
                            webPreferences: {
                                nodeIntegration: true
                            }
                        })
                        editWin.loadFile('edit.html')
                        editWin.on('ready-to-show', () => {
                            editWin.show()
                            editWin.setSize(1280, 768)
                            editWin.center()
                        })
                        editWin.webContents.on('did-finish-load', () => {
                            editWin.webContents.send('add', item.FNO)
                        })
                        editWin.on('closed', () => {
                            editWin = null
                            this.fetch()
                        })
                    }
                })
            )
            menu.append(
                new MenuItem({
                    label: '修改' + item.RFcode,
                    click: () => {
                        let editWin = new remote.BrowserWindow({
                            parent: remote.getCurrentWindow(),
                            minWidth: 1024,
                            minHeight: 768,
                            center: true,
                            modal: true,
                            show: false,
                            webPreferences: {
                                nodeIntegration: true
                            }
                        })
                        editWin.loadFile('edit.html')
                        editWin.on('ready-to-show', () => {
                            editWin.show()
                            editWin.setSize(1024, 768)
                            editWin.center()
                        })
                        editWin.webContents.on('did-finish-load', () => {
                            editWin.webContents.send('item', item)
                        })
                        editWin.on('closed', () => {
                            editWin = null
                            this.fetch()
                        })
                    }
                })
            )
            menu.append(
                new MenuItem({
                    label: '删除' + item.RFcode,
                    click: () => {
                        dialog.showMessageBox(
                            remote.getCurrentWindow(),
                            {
                                type: 'warning',
                                message: `确定要删除 ${item.RFcode} ?`,
                                buttons: ['取消', '确定']
                            },
                            async index => {
                                if (index === 1) {
                                    await db.delOne(item.RFcode)
                                    this.fetch()
                                }
                            }
                        )
                    }
                })
            )
            menu.popup(remote.getCurrentWindow())
            this.focus()
        },
        async fetch() {
            this.rfItemList = await db.findAll()
            this.categories = await db.findCategories()
            this.last()
        }
    },
    async created() {
        setInterval(() => {
            this.timeString = dayjs().format('YYYY-MM-DD HH:mm:ss')
        }, 1000)
        this.fetch()
        fs.exists('图片', exists => {
            if (exists) {
                fs.stat('图片', (err, stat) => {
                    if (err) return
                    if (!stat.isDirectory()) {
                        fs.mkdir('图片', err => {
                            if (err) return
                        })
                    }
                })
            } else {
                fs.mkdir('图片', err => {
                    if (err) return
                })
            }
        })
    },
    mounted() {
        this.focus()
    }
})

// ipcMain.on('closeEdit', (event, needFlush) => {
//     if (editWin != null) editWin.destroy()
//     if (needFlush) app.fetch()
// })
// document.getElementsByClassName('input')[0].focus()
